import { Controller, Get, Post, Body, HttpException, HttpStatus } from '@nestjs/common';
import { WorkflowService } from './workflow.service';

@Controller('workflow')
export class WorkflowController {
  constructor(private readonly workflowService: WorkflowService) {}

  @Get('health')
  health() {
    return { ok: true };
  }

  @Post('list')
  async list(@Body() body: any) {
    // eslint-disable-next-line no-console
    console.log('[WorkflowController] list - Received body:', JSON.stringify(body));

    // 允许 body 为空或传递所有字段给工作流
    const params: any = {
      ...body,
    };

    // 如果没有 subject，设置为空字符串
    if (!params.subject) {
      params.subject = '';
    }

    try {
      const result = await this.workflowService.runWorkflowWithCustomParams(params, 'COZE_WORKFLOW_LIST_ID');
      return { ok: true, result };
    } catch (err: any) {
      const message = err?.message || 'Internal server error';
      if (message.includes('COZE_TOKEN')) {
        throw new HttpException({ error: 'Server missing COZE_TOKEN configuration' }, HttpStatus.INTERNAL_SERVER_ERROR);
      }
      if (message.includes('COZE_WORKFLOW_LIST_ID')) {
        throw new HttpException({ error: 'Missing COZE_WORKFLOW_LIST_ID configuration' }, HttpStatus.INTERNAL_SERVER_ERROR);
      }
      throw new HttpException({ error: 'Failed to run workflow list', details: message }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Post('run')
  async run(@Body() body: any) {
    const subject = (body && body.subject) || '';
    const total = body?.total !== undefined ? Number(body.total) : 1;
    const min = body?.min !== undefined ? Number(body.min) : undefined;
    const max = body?.max !== undefined ? Number(body.max) : undefined;

    if (!subject) {
      throw new HttpException({ error: 'subject is required' }, HttpStatus.BAD_REQUEST);
    }

    try {
      const result = await this.workflowService.runWorkflow({ subject, total, min, max });
      return { ok: true, result };
    } catch (err: any) {
      const message = err?.message || 'Internal server error';
      if (message.includes('COZE_TOKEN')) {
        throw new HttpException({ error: 'Server missing COZE_TOKEN configuration' }, HttpStatus.INTERNAL_SERVER_ERROR);
      }
      throw new HttpException({ error: 'Failed to run workflow' }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}


